package com.jack.leetcode.eachProblem08;

import java.util.ArrayList;
import java.util.List;

public class 复原IP地址 {

    public static void main(String[] args) {
        restoreIpAddresses("010010");
    }

    public static List<String> restoreIpAddresses(String s) {
        if (s.isEmpty()) {
            return new ArrayList<>();
        }
        int m = s.length();
        if (m < 4) {
            return new ArrayList<>();
        }

        List<String> result = new ArrayList<>();
        for (int i = 1; i < 4; i++) {
            if (s.charAt(0) == '0' && i > 1) {
                continue;
            }
            String first = s.substring(0, i);
            Integer firstValue = Integer.valueOf(first);
            if (firstValue > 255) {
                continue;
            }
            for (int j = i + 1; j < i + 4 && j < m; j++) {
                if (s.charAt(i) == '0' && j > i + 1) {
                    continue;
                }
                String second = s.substring(i, j);
                Integer secondValue = Integer.valueOf(second);
                if (secondValue > 255) {
                    continue;
                }
                for (int k = j + 1; k < j + 4 && k < m; k++) {
                    if (s.charAt(j) == '0' && k > j + 1) {
                        continue;
                    }
                    String third = s.substring(j, k);
                    Integer thirdValue = Integer.valueOf(third);
                    if (thirdValue > 255) {
                        continue;
                    }
                    if (s.charAt(k) == '0' && k < m - 1) {
                        continue;
                    }
                    String fourth = s.substring(k, m);
                    if (fourth.isEmpty() || fourth.length() > 3) {
                        continue;
                    }
                    Integer fourthValue = Integer.valueOf(fourth);
                    if (fourthValue > 255) {
                        continue;
                    }
                    StringBuilder tmp = new StringBuilder(first).append(".")
                            .append(second).append(".").append(third).append(".").append(fourth);
                    System.out.println(tmp);
                    result.add(tmp.toString());
                }
            }
        }
        return result;
    }

}
